import { ref } from 'vue'
import { defineStore } from 'pinia'
import { defaultLayoutSetting, LayoutSettingkey, type LayoutSetting } from '@/config/layout/index'
import { getLocal, setLocal } from '@/utils/cache'

export const useLayoutStore = defineStore('layout', () => {
  const layoutSetting = ref<LayoutSetting>({})
  // 刷新之后，会多次stringify
  const getLayout = () => {
    const layoutStr = getLocal(LayoutSettingkey)
    if (layoutStr) {
      try {
        const layoutObj = JSON.parse(layoutStr) as LayoutSetting
        if (layoutObj) {
          return layoutObj
        } else {
          return defaultLayoutSetting
        }
      } catch (e) {
        console.log(e)
        return defaultLayoutSetting
      }
    } else {
      return defaultLayoutSetting
    }
  }

  const setLayout = (obj: LayoutSetting) => {
    layoutSetting.value = JSON.parse(JSON.stringify(obj))
    setLocal(LayoutSettingkey, layoutSetting.value)
  }
  const setDefault = () => {
    setLayout(defaultLayoutSetting)
  }
  const initLayout = () => {
    setLayout(getLayout())
  }
  return {
    layoutSetting,
    getLayout,
    setLayout,
    setDefault,
    initLayout
  }
})
